<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="no.ntnu.tdt4237.*"%>
<%@page import="no.ntnu.tdt4237.helperactions.*"%>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<tags:header title=" - Reset password"></tags:header>

<body>

	<tags:menu></tags:menu>
	<%
		if (request.getParameter("resetEmail") != null) {
			String email = request.getParameter("resetEmail");
			if (Database.isEmailValid(email) && Database.emailIsUsed(email)) {
				String username = Database.getUserName(email);	
				Database.setNewStatus(username, 1);
				String temp = Database.hashString(String.valueOf(System.currentTimeMillis()));
				Database.setPassword(temp, username);
				MailSender.sendNewPassword(email, Database.hashString(temp));
				session.setAttribute(SessionKeys.RESETTING_PASSWORD, session.hashCode());
	%>  
	<tags:resetpassword email="<%=email %>"></tags:resetpassword>
	<%
		}else{
			out.println("Your email is not valid");
		}
		} else if (request.getParameter("resetCode") != null && request.getParameter("newPassword") != null
				&& request.getParameter("email") != null && session.getAttribute(SessionKeys.RESETTING_PASSWORD) != null) {
			String resetcode = request.getParameter("resetCode");
			String newPassword = request.getParameter("newPassword");
			String email = request.getParameter("email");
			String username = Database.getUserName(email);
			if (Database.login(username, resetcode, true)){
				Database.setNotNew(username);
				Database.setPassword(Database.hashString(newPassword), username);
				 %>
				 <tags:message message="Your password has been reset!"></tags:message>
				 <%
			}else{
				 %>
				 <tags:message message="Your password has not been reset. Did you use the right activationcode?"></tags:message>
				 <%
			}
			
			session.removeAttribute(SessionKeys.RESETTING_PASSWORD);
			
		}else{
	%>
	<tags:sendresetmail></tags:sendresetmail>
	<%
		}
	%>

</body>
</html>